@extends('mdui.layouts.main')
@section('title', '微信文件分享工具')
@section('content')
    <div class="mdui-row mdui-m-t-2" data-v-0c2a5718=""><div class="mdui-col mdui-text-center" data-v-0c2a5718=""><div class="mdui-typo" data-v-0c2a5718=""><div class="mdui-typo-headline" data-v-0c2a5718=""><span class="mdui-text-color-theme mdui-color-green" data-v-0c2a5718="">WeShare</span></div><div class="mdui-typo-body-2-opacity" data-v-0c2a5718="">让文件分享更加便利</div></div></div></div>
    <div class="mdui-m-t-5">
        <div class="mdui-row mdui-m-t-3">
{{--            <div class="mdui-typo-title-opacity">微信长视频分享工具</div>--}}
{{--            <br>--}}
            <div class="mdui-typo-body-2-opacity" style="word-wrap: break-word;line-height: 20px;">
                <ul>
                    <li style="color: green;padding: 5px;">突破微信分享文件大小限制</li>
                    <li style="color: green;padding: 5px;">手机/电脑/IPAD文件互传</li>
                    <li style="color: green;padding: 5px;">上传/下载不限速，一键分享</li>
                    <li style="color: green;padding: 5px;">多种视频格式支持在线播放</li>
                </ul>
            </div>
            <br>

            <div class="mdui-tab mdui-tab-centered" mdui-tab>
                <a class="mdui-ripple mdui-tab-active" href="#uploadFile">上传文件</a>
                <a class="mdui-ripple" href="#getFile">提取文件</a>
            </div>
            <div  id="uploadFile">

                <Br>
                <div class="mdui-typo-body-2-opacity" style="word-wrap: break-word;line-height: 23px;">您可以尝试文件拖拽或者点击虚线框进行文件上传，单文件最大支持10G.</div>
                <br>
                <input type="file" class="filepond" name="olaindex_img" multiple="true" data-max-file-size="10240MB"
                       data-max-files="1" data-instant-upload="true"
                       accept="image/*,audio/*,video/*,text/*,application/*"/>
                <br>


                <div style="padding: 15px 0;color: grey;" id="progress" class="mdui-hidden"></div>
                <div class="mdui-typo-body-2-opacity mdui-hidden" id="uploading" style="color: grey; word-wrap: break-word;line-height: 23px;"><i class="mdui-icon material-icons" style="margin-top: -3px">sync</i> 正在上传，请勿关闭浏览器！</div>
                <div class="mdui-typo-body-2-opacity mdui-hidden" id="uploading-success" style="color: green; word-wrap: break-word;line-height: 23px;"><i class="mdui-icon mdui-text-color-green material-icons" style="margin-top: -3px">check_circle</i> 上传成功，你可以复制链接分享给好友</div>
                <div class="mdui-typo-body-2-opacity mdui-hidden" id="uploading-failed" style="color: red; word-wrap: break-word;line-height: 23px;"><i class="mdui-icon mdui-text-color-red material-icons" style="margin-top: -3px">warning</i> 上传失败，请重新上传</div>
                <P id="tip"></P>

                <div id="showUrl" class="mdui-hidden">
                    <div class="mdui-tab" mdui-tab>
                        <a class="mdui-ripple" href="#urlCode">下载链接</a>
                        {{--<a class="mdui-ripple" href="#htmlCode">HTML</a>--}}
                        {{--<a class="mdui-ripple" href="#bbCode">BBCODE</a>--}}
                        {{--<a class="mdui-ripple" href="#markdown">MD</a>--}}
                        {{--<a class="mdui-ripple" href="#markdownLinks">MD LINK</a>--}}
                    </div>
                    <div class="mdui-p-a-2 mdui-m-t-2 mdui-shadow-3" id="urlCode"></div>
                    {{--<div class="mdui-p-a-2 mdui-m-t-2 mdui-shadow-3" id="htmlCode"></div>--}}
                    {{--<div class="mdui-p-a-2 mdui-m-t-2 mdui-shadow-3" id="bbCode"></div>--}}
                    {{--<div class="mdui-p-a-2 mdui-m-t-2 mdui-shadow-3" id="markdown"></div>--}}
                    {{--<div class="mdui-p-a-2 mdui-m-t-2 mdui-shadow-3" id="markdownLinks"></div>--}}
                    <div class="mdui-typo mdui-m-t-2" style="text-align: center;">
                        <a href="#" target="_blank" id="preview-url" style="color: white;" class="mdui-btn-raised">
                            <button
                                class="clipboard mdui-btn mdui-btn-raised mdui-btn-dense mdui-ripple mdui-color-green-800 mdui-inline-block">
                                <i class="mdui-icon material-icons">launch</i> 查看文件
                            </button>
                        </a>
                        <button
                            data-clipboard-target="#urlCode"
                            class="clipboard mdui-btn mdui-btn-raised mdui-btn-dense mdui-ripple mdui-color-theme-accent mdui-inline-block">
                            <i class="mdui-icon material-icons">content_copy</i> 复制链接
                        </button>

                    </div>

                    <div class="mdui-typo-body-2-opacity" style="color: grey; word-wrap: break-word;line-height: 22px;margin-top:50px;padding: 25px 0;">
                        <p>申明：此网站仅用于临时文件分享，文件最多可保留30天，如有需要，请及时保存到本地</p>
                    </div>
                </div>





            </div>
            <div  id="getFile">
                <div class="fetch-container mdui-m-t-2">
                    <form _lpchecked="1">
                        <div class="mdui-textfield">
                            <i class="mdui-icon material-icons">search</i><input class="mdui-textfield-input" type="text" placeholder="输入提取码"></div>
                        <div class="mdui-textfield"><button type="submit" class="search-btn mdui-btn mdui-color-theme mdui-ripple mdui-btn-raised mdui-float-right"> 搜索 </button></div></form>
                </div>
            </div>

        </div>


    </div>
@stop
@push('stylesheet')
    <link rel="stylesheet" href="/css/filepond.min.css">
{{--    <link rel="stylesheet"--}}
{{--          href="/css/filepond-plugin-image-preview.min.css">--}}
{{--    <link rel="stylesheet" href="/css/filepond-plugin-media-preview.css">--}}
@endpush
@push('scripts')
{{--    <script src="/js/socket.io.min.js"></script>--}}
    <script src="/js/progressbar.min.js"></script>
    <script src="/js/filepond-plugin-media-preview.js"></script>
{{--    <script src="/js/filepond-plugin-file-rename.js"></script>--}}
    <script>

        // const soc = io.connect('http://1.15.100.180:9090/')
        // //向指定的服务器建立连接，地址可以省略
        // soc.emit('msg','你好服务器');
        // //自定义msg事件，发送‘你好服务器’字符串向服务器
        // soc.on('msg',(data)=>{
        //     //监听浏览器通过msg事件发送的信息
        //     console.log(data);//你好浏览器io.connect('ws://localhost:8080/')
        // });
        //
        // soc.on('upload',(data)=>{
        //     //修改进度条状态
        //     console.log(data)
        //     window.bar.animate(data);
        // });
        //
        // // client-side
        // soc.on("connect", () => {
        //     window.socket_id = soc.id
        //     console.log(soc.id); // x8WIv7-mJelg7on_ALbx
        //
        // });
        //
        // soc.on("disconnect", () => {
        //     console.log(soc.id); // undefined
        // });



    </script>
    <script src="/js/filepond.min.js"></script>
{{--    <script--}}
{{--        src="/js/filepond-plugin-image-preview.min.js"></script>--}}
    <script
        src="/js/filepond-plugin-file-validate-size.min.js"></script>
    {{--<script src="https://cdn.jsdelivr.net/npm/filepond-plugin-file-validate-type@1.2.5/dist/filepond-plugin-file-validate-type.min.js"></script>--}}
    <script>
        $(function (){


            var start,contentLength,content,end,filesize


            var __FILE

            var length = 10000000 //默认上传速度10M

            var DownloadUrl //文件下载链接

            var startTime //开始时间

            var CancelToken = axios.CancelToken //取消上传
            var CancelRequest

            var noSleep = new NoSleep();//禁止息屏

            const $http = axios.create({
                // baseURL: '/api/',
                // timeout: 5000 // request timeout
            })

            // http response 拦截器
            axios.interceptors.response.use(response => {
                const data = response.data;
                // if(!data){
                //     console.log("返回结果不对")
                // }
                // console.log(response)
                // 根据返回的code值来做不同的处理(和后端约定)
                // switch (data.code) {
                //     case 210:
                //         Toast(data.message);
                //         break;
                //     // 错误
                //     case 500:
                //         Toast("联系管理员");
                //         break;
                //     default:
                //         return data;
                // }

                return data;
            }, (err) => {
                // 返回状态码不为200时候的错误处理
                // Toast('连接错误，请重试');

                if (axios.isCancel(err)) {
                    console.log('用户终止了上传：', err.message)
                    return Promise.reject(err);
                }
                // if (!isGenericError(err)) {
                //     return Promise.reject(err);
                // }


                // var config = err.config;

                //全局请求重试

                // retry和retryDelay 可以在传的参数里面携带
                if (config.headers&& !config.headers.retry) {
                    config.headers.retry = 5;//设置默认重复次数
                }
                config.headers.__retryCount = config.headers.__retryCount || 0;
                if (config.headers.__retryCount >= config.headers.retry) {
                    alert("网络错误，请重试");
                    return Promise.reject(err);
                }
                config.headers.__retryCount += 1;
                var backoff = new Promise(function(resolve) {
                    setTimeout(function() {
                        resolve();
                    },2000);
                });
                return backoff.then(function() {
                    return axios(config);
                });

            });


            window.bar = new ProgressBar.Line("#progress", {

                easing: 'easeInOut',
                duration: 700,
                color: '#FFEA82',
                trailColor: '#eee',
                trailWidth: 1,
                strokeWidth: 2.1,
                svgStyle: {width: '100%', height: '100%'},
                // text: {
                //     style: {
                //         // Text color.
                //         // Default: same as stroke color (options.color)
                //         color: '#999',
                //         position: 'absolute',
                //         right: '0',
                //         top: '30px',
                //         padding: 0,
                //         margin: 0,
                //         transform: null
                //     },
                //     autoStyleContainer: false
                // },
                from: {color: '#32302f'},
                to: {color: '#0f9960'},
                step: (state, bar) => {
                    bar.path.setAttribute('stroke', state.color);
                    // bar.setText(Math.round(bar.value() * 100) + ' %');
                }
            });

            FilePond.registerPlugin(
                // FilePondPluginImagePreview,
                FilePondPluginFileValidateSize,
                // FilePondPluginFileValidateType,
                // FilePondPluginMediaPreview,
            )
            FilePond.setOptions({
                labelIdle: '拖放文件，或者 <span class="filepond--label-action"> <i class="mdui-icon material-icons" style="margin-top: -2px;">add_circle_outline</i> 手动添加 </span>',
                dropOnPage: true,
                dropOnElement: true,
                dropValidation: true,
                allowProcess: true,
                labelFileProcessing: "上传中...",
                labelFileProcessingComplete: "上传成功",
                labelTapToCancel: "点击取消",
                labelTapToUndo: "点击撤销",
                labelFileProcessingAborted: "上传已被取消",
                labelTapToRetry: "点击重新上传",
                labelFileProcessingError: "上传失败",
                server: {
                    url: App.routes.upload_image,
                    process:(fieldName, file, metadata, load, error, progress, abort, transfer, options) => {


                        $('#showUrl').addClass('mdui-hidden')
                        $('#urlCode').empty()
                        $("#progress").removeClass("mdui-hidden");
                        $("#uploading").removeClass("mdui-hidden");
                        $("#uploading-failed").addClass('mdui-hidden')
                        $("#uploading-success").addClass('mdui-hidden')
                        $("#tip").empty()

                        //记录开始时间
                        startTime =  parseInt(Date.parse(new Date()) / 1000);


                        noSleep.enable(); // keep the screen on!


                        var formData = new FormData()
                        formData.append('filename', __FILE.name)


                        axios.post('/api/uploadinfo',formData)
                            .then(res=>{

                                // console.log('res=>',res);
                                DownloadUrl = res.url


                                uploadUrl = res.uploadUrl
                                token = res.token


                                start = 0;
                                filesize = __FILE.size
                                contentLength = filesize > length ? length : filesize;
                                // content = file.file.slice(start, contentLength)
                                end = start + contentLength - 1;
                                content = blobSlice(__FILE, start, contentLength)


                                return {
                                    file:__FILE,
                                    token:token,
                                    uploadUrl:uploadUrl,
                                    content:content,
                                    start:start,
                                    end:end
                                }
                            }).then(function (res) {

                            upload(res.uploadUrl,res.token,res.content,res.start,res.end,res.file).then(function(){

                                noSleep.disable(); // let the screen turn off.

                                console.log('done.')
                            })

                        }).catch(function (error) {
                            console.log(error)
                        })




                        //递归上传

                        function upload(uploadUrl,token,content,start,end,file){
                            return new Promise(function(resolve,reject){

                                axios.put(uploadUrl,content,{
                                    headers: {
                                        'Authorization':"bearer "+token,
                                        "Content-Range": "bytes "+start+"-"+end+"/"+file.size
                                    },
                                    cancelToken: new CancelToken(function executor(c) {
                                        // 1. cancel函数赋值给cancelRequest属性
                                        // 从而可以通过cancelRequest执行取消请求的操作
                                        CancelRequest = c
                                    }),
                                }).then(res=>{//成功
                                    let data = res

                                    //更新进度条
                                    progress(true, end+1, file.size);
                                    window.bar.animate((end+1)/file.size)

                                    if(data.file){//上传完成
                                        reject('上传成功')



                                        axios.get("/api/cacherefresh")
                                        load("上传成功");
                                        $("#uploading").addClass("mdui-hidden");
                                        $("#uploading-success").removeClass("mdui-hidden");

                                        $('#showUrl').removeClass('mdui-hidden')
                                        $('#urlCode').append('<p style="word-wrap: break-word;line-height: 20px;">' + DownloadUrl + '</p>')
                                        // $('#htmlCode').append('<p style="word-wrap: break-word;line-height: 20px;">&lt;img src=\'' + DownloadUrl + '\' alt=\'' + __FILE.name + '\' title=\'' + __FILE.name + '\' /&gt;' + '</p>')
                                        // $('#bbCode').append('<p style="word-wrap: break-word;line-height: 20px;">[img]' + DownloadUrl + '[/img]' + '</p>')
                                        // $('#markdown').append('<p style="word-wrap: break-word;line-height: 20px;">![' + __FILE.name + '](' + DownloadUrl + ')' + '</p>')
                                        // $('#markdownLinks').append('<p style="word-wrap: break-word;line-height: 20px;">[![' + __FILE.name + '](' + DownloadUrl + ')]' + '(' + DownloadUrl + ')' + '</p>')


                                        $('#preview-url').attr("href",DownloadUrl)
                                        let total_time = parseInt(Date.parse(new Date()) / 1000) - startTime
                                        $("#tip").append("（用时："+total_time+"秒，上传速度："+bytesToSize(__FILE.size/total_time)+"/s）")


                                    }else{

                                        // sleep(500)

                                        resolve(data)
                                    }
                                }).catch(function (error) {

                                    if (axios.isCancel(error)) {
                                        console.log('用户终止了上传：', error.message)
                                    }
                                    console.log(error)

                                    reject(error)


                                    if (typeof error == 'object') {
                                        $("#showUrl").after((JSON && JSON.stringify ? JSON.stringify(error) : error) + '<br />')
                                    } else {
                                        $("#showUrl").after(error)
                                    }

                                    $("#uploading").addClass("mdui-hidden");
                                    $("#uploading-failed").removeClass("mdui-hidden");
                                })


                            }).then(function(data){



                                let nextExpectedRanges = data.nextExpectedRanges[0].split('-');

                                let start_index= parseInt(nextExpectedRanges[0]);
                                let end_index = parseInt(nextExpectedRanges[1]);

                                let start = parseInt(nextExpectedRanges[0]);
                                let contentLength = ( parseInt(start+length-1) > (parseInt(file.size)-1) ) ? parseInt(end_index-start_index+1 ): length;

                                let end = start + contentLength - 1;
                                let content = blobSlice(__FILE, start, start + contentLength)

                                return upload(uploadUrl,token,content,start,end,file)
                            },function (error) {
                                console.log(error)
                            })
                        }

                        function bytesToSize(bytes) {
                            if (bytes === 0) return '0 B';
                            var k = 1000, // or 1024
                                sizes = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'],
                                i = Math.floor(Math.log(bytes) / Math.log(k));

                            return (bytes / Math.pow(k, i)).toPrecision(3) + ' ' + sizes[i];
                        }

                        function blobSlice(blob, start, length) {
                            if(blob.slice) {
                                return blob.slice(start, length);
                            } else if (blob.webkitSlice) {
                                return blob.webkitSlice(start, length);
                            } else if (blob.mozSlice) {
                                return blob.mozSlice(start, length);
                            } else {
                                return null;
                            }
                        }


                        return {
                            abort: (err) => {
                                // This function is entered if the user has tapped the cancel button
                                pond.FileStatus = 6

                                // Let FilePond know the request has been cancelled
                                abort();
                            }
                        };

                    },
                    // process: {
                    //     url: '/',
                    //     method: 'POST',
                    //     withCredentials: false,
                    //     headers: {},
                    //     timeout: 1000*60*60,
                    //     onload: (response) => {
                    //         let res = JSON.parse(response)
                    //         if (res.code === 0) {
                    //             $('#showUrl').removeClass('mdui-hidden')
                    //             $('#urlCode').append('<p style="word-wrap: break-word;line-height: 20px;">' + res.data.url + '</p>')
                    //             $('#htmlCode').append('<p style="word-wrap: break-word;line-height: 20px;">&lt;img src=\'' + res.data.url + '\' alt=\'' + res.data.filename + '\' title=\'' + res.data.filename + '\' /&gt;' + '</p>')
                    //             $('#bbCode').append('<p style="word-wrap: break-word;line-height: 20px;">[img]' + res.data.url + '[/img]' + '</p>')
                    //             $('#markdown').append('<p style="word-wrap: break-word;line-height: 20px;">![' + res.data.filename + '](' + res.data.url + ')' + '</p>')
                    //             $('#markdownLinks').append('<p style="word-wrap: break-word;line-height: 20px;">[![' + res.data.filename + '](' + res.data.url + ')]' + '(' + res.data.url + ')' + '</p>')
                    //             var time = ((res.data.size/5000000)*(10)/60).toFixed(1);
                    //             if(time < 1) time = ((res.data.size/8000000)*(0.5+2)).toFixed(1) + "秒"
                    //             else time = time + "分钟"
                    //             $('#progress').append('<p style="word-wrap: break-word;line-height: 23px;">正在将资源上传到云端，云端处理需要一定时间，预计需要'+time+'，您可以先将以下链接保存或分享给好友👇</p>')
                    //
                    //         }
                    //         return response.key
                    //     },
                    //     onerror: (response) => response.data,
                    //     ondata: (formData) => {
                    //         formData.append('_token', App._token)
                    //         return formData
                    //     },
                    // },
                    revert: null,
                    restore: null,
                    load: null,
                    fetch: null,
                },
            })


            const pond = FilePond.create(document.querySelector('input[name=olaindex_img]'), {
                // acceptedFileTypes: ['image/*','audio/*','video/*','text/*','application/*'],
            })
            pond.on('addfile', (error, file) => {
                // console.log(error)
                // console.log(file)
                // console.log(file.file)
                // var reader = new FileReader();
                // reader.readAsArrayBuffer(file.file)
                // reader.onload = function(ev) {
                //     // console.log(this.result);//二进制流
                //
                //     var bytes = new Uint8Array(this.result);
                //     // 头信息
                //     // const fileHead1 = bytes.slice(0, 40);
                //     // const bodyData = bytes.slice(40, bytes.length);
                //     // console.log(fileHead1)
                //     // console.log(bodyData)
                //     // console.log(file.file.size)
                //     // console.log(file.fileSize)
                //
                //     __FILE = file.file
                //     console.log(__FILE.slice(99999,199999))
                //     console.log(__FILE.size)
                //     console.log(__FILE.slice(299999,399999))
                //
                //     __FILE = bytes
                //     console.log(__FILE.slice(99999,199999))
                //     console.log(__FILE.size)
                //     console.log(__FILE.slice(299999,399999))
                //
                //
                // }
                    __FILE = file.file
                if(__FILE.size > 0 && __FILE.size < 100000000){
                    //小于100M的文件上传速度 10M
                    length = 10000000
                }

                if(__FILE.size > 100000000 && __FILE.size < 500000000){
                        //200M-500M的文件上传速度 20M
                        length = 20000000
                }
                if(__FILE.size > 500000000 && __FILE.size < 1000000000){
                    //500M-1G的文件上传速度 30M
                    length = 30000000
                }
                if(__FILE.size > 1000000000){
                    //大于1G的文件上传速度 50M
                    length = 50000000
                }

                // 修改文件名按钮
                // $("")

            })
            pond.on('processfile', (error, file) => {
                if (error) {
                    console.log('上传出错了')
                    console.log(error)
                    return
                }
                // console.log('文件已上传', file)

            })
            pond.on('removefile', (file) => {
                console.log('文件已删除', file)
                __FILE = null
            })
            pond.on("processfilestart", (file) => {

                window.bar.animate(0)
                // console.log('文件开始上传', file)
            })
            pond.on('processfileprogress', (file, progress) => {
                // console.log('文件正在上传', file)
                window.bar.animate(progress)
            })
            pond.on('processfileabort', (file) => {
                // console.log('文件正在上传', file)
                window.bar.animate(0)
                console.log("文件上传中断");

                if (typeof CancelRequest === 'function') {
                    CancelRequest('网络错误或上传中断，请重试')
                }

            })

        })


    </script>

@push('scripts')
    <script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
    <ins class="adsbygoogle"
         style="display:block"
         data-ad-format="fluid"
         data-ad-layout-key="-fb+5w+4e-db+86"
         data-ad-client="ca-pub-6243451787655828"
         data-ad-slot="8925134107"></ins>
    <script>
        (adsbygoogle = window.adsbygoogle || []).push({});
    </script>
@endpush

<script src="/js/noSleep.js"></script>
@endpush
